<?php
/*
 * Created on Feb 19, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
include('../includes/session.php');
include('../models/reesnew_model.php');

class ReesItemController{
	
	function ReesItemController(){
		global $session;
		if(isset($_POST['itemedit'])){
        	$this->itemEdit();
     	}else if(isset($_POST['itemadd'])){
        	$this->itemAdd();
     	}else if(isset($_POST['itemsearch'])){
        	$this->itemSearch();
     	}else if(isset($_POST['itemsearchadmin'])){
        	$this->itemSearchAdmin();
     	}elseif(isset($_GET['type']) && ($_GET['type'] == 'deleteitem') && isset($_GET['itemid'])) {
     		$this->deleteRees($_GET['itemid']);
     	}
     	else {
        	header("Location: ".$session->referrer);
       	}
	}
	
	function deleteRees($id){
		global $form, $reesNewModel;
		$result = $reesNewModel->deleteRees($id);
		if($result == 0){
			$_SESSION['myActionDeleteSuccess'] = 'true';
		}else{
			$_SESSION['myActionDeleteError'] = 'true';
		}
		header("Location: ../myestate.php");
	}
	
	
	function itemSearch(){
		global $session;
		$stringGet = '';
		foreach($_POST as $key => $value){
			if(!empty($value))
				$stringGet .= '&'.$key.'='.$value;
		}
		header("Location: ../search.php?".$stringGet);
	}
	
	function itemSearchAdmin(){
		global $session;
		$stringGet = '';
		foreach($_POST as $key => $value){
			if(!empty($value))
				$stringGet .= '&'.$key.'='.$value;
		}
		header("Location: ../admincp/searchreess.php?".$stringGet);
	}
	
	function itemAdd(){
		global $session, $form;
		$resultValidation = 0;
		$arrayData = array();
		$arrayData['title'] = $_POST['title'];
		$arrayData['address'] = $_POST['address'];
		$arrayData['size'] = $_POST['size'];
		$arrayData['price'] = $_POST['price'];
		$arrayData['description'] = $_POST['description'];
		$arrayData['content'] = $_POST['content'];
		$arrayData['contact'] = $_POST['contact'];
		$arrayData['source'] = $_POST['source'];
		$arrayData['reestype'] = $_POST['reestype'];
		$arrayData['typehouse'] = $_POST['typehouse'];
		$arrayData['region'] = $_POST['region'];
		$arrayData['city'] = $_POST['city'];
		$arrayData['district'] = $_POST['district'];
		$arrayData['direction'] = $_POST['direction'];
		$arrayData['createDate'] = $_POST['createDate'];
		$arrayData['endDate'] = $_POST['endDate'];
		$arrayData['userId'] = $_POST['userId'];
		$arrayData['isSpecial'] = $_POST['isSpecial'];
		
		$resultValidation = $this->checkValidation(
										null,
										$arrayData,
										$_FILES['image']);
		
		/* Add Successful */
		if($resultValidation == 0){
	    	$_SESSION['successname'] = $_POST['title'];
	        $_SESSION['success'] = true;			
	        header("Location: ".$session->referrer);
	    }
	    /* Error found with form */
	    else if($resultValidation == 1){
	        $_SESSION['value_array'] = $_POST;
	        $_SESSION['error_array'] = $form->getErrorArray();			
	        header("Location: ".$session->referrer);
	    }
	    /* Add attempt failed */
	    else if($resultValidation == 2){
	        $_SESSION['successname'] = $_POST['title'];
	        $_SESSION['success'] = false;			
	        header("Location: ".$session->referrer);
		}
	}
	
	function itemEdit(){
		global $session, $form;		
		$resultValidation = 0;
		$arrayData = array();
		$arrayData['title'] = $_POST['title'];
		$arrayData['address'] = $_POST['address'];
		$arrayData['size'] = $_POST['size'];
		$arrayData['price'] = $_POST['price'];
		$arrayData['description'] = $_POST['description'];
		$arrayData['content'] = $_POST['content'];
		$arrayData['contact'] = $_POST['contact'];
		$arrayData['source'] = $_POST['source'];
		$arrayData['reestype'] = $_POST['reestype'];
		$arrayData['typehouse'] = $_POST['typehouse'];
		$arrayData['region'] = $_POST['region'];
		$arrayData['city'] = $_POST['city'];
		$arrayData['district'] = $_POST['district'];
		$arrayData['direction'] = $_POST['direction'];
		$arrayData['createDate'] = $_POST['createDate'];
		$arrayData['endDate'] = $_POST['endDate'];
		$arrayData['userId'] = $_POST['userId'];
		$arrayData['isSpecial'] = $_POST['isSpecial'];
		
		$resultValidation = $this->checkValidation(
										$_POST['SelectedRees'],
										$arrayData,
										$_FILES['image']);
										
		/* Account edit successful */
	    if($resultValidation == 0){
	    	$_SESSION['edit'] = true;
			$_SESSION['editname'] = $_POST['title'];
	        header("Location: ".$session->referrer);
	    }
	    /* Error found with form */
	    else{
	        $_SESSION['value_array'] = $_POST;
	        $_SESSION['error_array'] = $form->getErrorArray();
	        header("Location: ".$session->referrer);
		}
	}
	
	function checkValidation($id = null, $arrayData = null, $image){
		global $form, $reesNewModel;
		/* title error checking */
		$field = "title";
	    if(!$arrayData['title'] || strlen($arrayData['title'] = trim($arrayData['title'])) == 0){
	    	$form->setError($field, prnMsg(_('Nhập tiêu đề tin'),'error'));
	    }
		$field = "description";
	    if(!$arrayData['description'] || strlen($arrayData['description'] = trim($arrayData['description'])) == 0){
	    	$form->setError($field, prnMsg(_('Nhập thông tin mô tả'),'error'));
	    }
		$field = "contact";
	    if(!$arrayData['contact'] || strlen($arrayData['contact'] = trim($arrayData['contact'])) == 0){
	    	$form->setError($field, prnMsg(_('Nhập liên hệ - điện thoại'),'error'));
	    }
				
		if(!$arrayData['sortNo'] || strlen($arrayData['sortNo'] = trim($arrayData['sortNo'])) == 0){
	    	$arrayData['sortNo'] = 0;
	    }
		
		if(!$arrayData['isSpecial'] || strlen($arrayData['isSpecial'] = trim($arrayData['isSpecial'])) == 0){
	    	$arrayData['isSpecial'] = 0;
	    }
		/* Errors image checking */
		$field = "image";  //Use field name for image
		$extention = "";
		if (isset($image) AND $image['name'] !='') {
			$extention = strtoupper(substr(trim($image['name']),strlen($image['name'])-3));
			 //But check for the worst
			if ($extention != 'JPG' && $extention != 'GIF' && $extention != 'PNG'){
				$form->setError($field, prnMsg(_('Chỉ hỗ trợ file ảnh dạng .jpg, .gif, .png'),'error'));
			} elseif ( $image['size'] > ($_SESSION['MaxFileUpload']*1024)) { //File Size Check
				$form->setError($field, prnMsg(_('Kích thước file vượt kích thước cho phép ('.$_SESSION['MaxFileUpload'].')'),'error'));				
			} elseif ( $image['type'] == "text/plain" ) {  //File Type Check
				$form->setError($field, prnMsg(_('Chỉ chấp nhận file dạng ảnh'),'error'));				
			}		
		}
		
		/* Errors exist, have user correct them */
	    if($form->num_errors > 0){
	    	return 1;  //Errors with form
	    }/* No errors, add the new account to the */
	    else{
	    	if(!isset($id)){
		        $result = $reesNewModel->addNewItem($arrayData);
				if($result == 0 && isset($image) AND $image['name'] != '' ){
		        	return $this->updateInfoImage($_SESSION['LastInsertId'], $image);		        	
				}
				return $result;
			}else{				
				$result = $reesNewModel->editItem($id, $arrayData);
				if($result == 0){
					return $this->updateInfoImage($id, $image);		        	
				}
				return $result;
			}
	   	}
	}
	
	function updateInfoImage($id = null, $image = null){
		global $reesNewModel, $form;
		if(isset($image) AND $image['name'] != '' ){
		   	$extention = strtoupper(substr(trim($image['name']),strlen($image['name'])-3));
			$filename = '../'.$_SESSION['PathUploadItem'].$id.'.'.$extention;
			$reesNewModel->updateImageField($id, $id.'.'.$extention);		        		        	
		   	$resultUpload  =  move_uploaded_file($image['tmp_name'], $filename);
			if(!$resultUpload){
				$field = "image";
				$form->setError($field, prnMsg(_('Quá trình upload file bị lỗi.'),'error'));
				return 2;		
			}	
		}
		return 0;
	}
};

/* Create transaction controller object */
$reesItemController = new ReesItemController;
?>